const config = require('config')
const stringRandom = require('string-random');
// 发送邮件模块

const nodemailer = require('nodemailer')
module.exports.sendemail = (req, res) => {

    const info = config.get('email')
    const { recipient, } = req.body
    const codes = this.verification || 0
    if (codes.length <= 1) {
        codes.forEach((item, index) => {
            if (item.email == recipient) {
                res.sendResult(null, 400, '你已经发送过验证码请等一会再发送！')
                return
            }
        })

    }

    if (!recipient) {
        res.sendResult(null, 400, '请传递收件人邮箱！')
        return
    }
    const reg = /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/
    if (!reg.test(recipient)) {
        res.sendResult(null, 400, '邮箱格式不正确！')
        return
    }
    var emailarr = this.verification || []
    emailarr.forEach((item, index) => {
        if (item.email == recipient) {
            emailarr.splice(index, 1);
        }
    })
    var emailobj = {
        email: recipient,
        Verification: stringRandom(5)
    }
    emailarr.push(emailobj)
    this.verification = emailarr
    // 配置邮箱
    var transporter = nodemailer.createTransport({
        host: info.host,
        // 端口
        port: info.port,
        // 开启安全连接
        secureConnection: true,
        secure: true,
        // 发件人配置
        auth: {
            // 邮箱账号
            user: info.user,
            // 授权码
            pass: info.pass
        },
    })

    // 发送内容
    var mailOptios = {
        // 发件人邮箱
        from: info.user,
        // 收件人邮箱
        to: recipient,
        // 邮件主题
        subject: 'XIAOKE图床邮箱验证',
        // 内容
        // text: "测试邮件"
        html: `
        <h1>尊敬的用户<h1/>
        <p>您刚刚在<span style="color:red;">XIAOKE图床</span>提出账号注册申请验证</p>
        <p>你的验证码是：<span style="color:red;">${emailobj.Verification}</span> </p>
        <p>验证码有效期：<span style="color:red;">2分钟</span></p>
        <div style="text-align: right;">
        <p>如果不是您主动注册或操作，请无视本邮件即可！</p>
        <p>感谢您的访问，祝您访问愉快，系统邮件请勿回复！</p>
        <p>——来自<span style="color:red;">XIAOKE图床</span></p>
        </div>
        `
    }

    // 发送
    transporter.sendMail(mailOptios, (err, info) => {
        if (err) {
            res.sendResult(null, 400, '邮箱不存在！，发送错误！')
            return
        } else {
            // console.log(this.verification);
            var i = 0
            var item = setInterval(() => {
                i++
                if (i == 120) {
                    this.verification.forEach((item, index) => {
                        if (item.email == recipient) {
                            this.verification.splice(index, 1)
                        }
                    })
                    clearInterval(item)

                }
            }, 1000)
            res.sendResult(null, 200, '发送邮件成功！')
            return
        }
    })
}
module.exports.code = this.verification


